import Config from './config'

var baseUrl = Config.baseUrl

var fns = [] // 请求集合

var HasLoading = false //是否有Loading

// 发起请求
export function http(params) {
    return new Promise((resolve, reject) => {
        return getData(params, resolve, reject)

        // if (!uni.getStorageSync('session')) {
        //     // 没有session 先去登陆获取
        //     fns.push(() => {
        //         getData(params)
        //     })

        // } else {
        //     getData(params)
        // }
    })
}

// Json 转换 字符串拼接 ，get 请求的时候用
function formatGet(json) {
    let paramsStr = ''

    Object.keys(json).map((key) => {
        if (json[key] && json[key] != 'undefined') {
            paramsStr += `${key}=${json[key]}&`
        }
    })

    return paramsStr
}

//封装的请求
function getData(params, resolve, reject) {
    let nomsg = false
    let url,
        data,
        method = 'get'
    let header = {
        'content-type': 'application/json',
        'x-access-token': uni.getStorageSync('token'),
    }

    if (typeof params === 'string') {
        url = params
    } else {
        //新增如果是get 参数多的情况 可以按照json格式传参
        if (params.transGet) {
            params.url += '?' + formatGet(params.data)
            params.data = {}
            params.method = 'get'
        }

        url = params.url
        data = params.data || {}
        method = params.method || 'post'
        params.header && Object.assign(axheader, params.header)
        nomsg = !!params.nomsg
    }

    var requireUrl = baseUrl

    //qmx 需要更换根目录地址
    if (url.indexOf('/API/') >= 0) {
        requireUrl = Config.qmxUrl
        url = url.replace('/API/', '')
    }

    if (url.indexOf('/pyimg/') >= 0) {
        requireUrl = Config.baseWebUrl
    }

    //loading
    if (url.includes('?loading')) {
        HasLoading = true

        uni.showLoading()
        url = url.replace('?loading', '')
    }
    //form
    if (url.includes('?form')) {
        header['content-type'] = 'application/x-www-form-urlencoded'
        url = url.replace('?form', '')
    }

    uni.request({
        url: requireUrl + url,
        data: data,
        header: header,
        method: method || 'get',
        success: (res) => {
            // console.log('看看怎么回事',res)

            if (res.statusCode == 200) {
                if (res.data.code == 200) {
                    resolve(res.data)
                } else {
                    if (!nomsg) {
                        uni.showToast({
                            title: res.data.msg || '请求失败,请稍后再试',
                            duration: 3000,
                            icon: 'none',
                        })
                    }

                    reject(res.data)
                }

                return
            } else if (res.statusCode == 401) {
                uni.showToast({
                    title: '登陆超时，请退出重新进入',
                    duration: 3000,
                    icon: 'none',
                })

                uni.removeStorageSync('token')

                return
            } else {
                console.log('222222222222222', res)

                uni.showToast({
                    title: res.data.message || '请求失败,请稍后再试',
                    duration: 3000,
                    icon: 'none',
                })
                return
            }

            resolve(res.data)
        },
        fail: (res) => {
            reject(res)
            console.log('请求错误', res)
        },
        complete: (res) => {
            if (HasLoading) {
                uni.hideLoading()
                HasLoading = false
            }
        },
    })
}

//图片上传
export function uploadFunc(url, filePath, obj = {} ,HasLoading) {
    return new Promise((resolve, reject) => {


        if(HasLoading){
            uni.showLoading()
        }

        uni.uploadFile({
            url: Config.qmxUrl + url,
            filePath: filePath,
            name: obj.name || 'file',
            header: obj.header || { 'content-type': 'multipart/form-data' },
            formData: obj.formData || {},
            success: (msg) => {
                if (HasLoading) {
                    uni.hideLoading()
                }
                // console.log('上传后消息', msg);

                if (msg.statusCode == 200) {
                    let resJson = JSON.parse(msg.data)

                    resolve(resJson)
                } else {
                    uni.showToast({
                        title: msg.errMsg,
                        icon: 'none',
                        duration: 3000,
                        success: (msg) => {},
                    })
                }

            },
            fail: (err) => {
                if (HasLoading) {

                    uni.hideLoading()
                }
                console.log('fail', err)
            },
            complete: (msg) => {},
        })
    })
}
//图片上传合集
//小程序自带的上传接口  不支持多图 只能循环 一张一张上传

export function uploadFuncMulti(url, filePath, obj,showToast) {
    url = url || 'zuul/api-f/files/uploadToDir'
    obj = obj || { formData: { directory: 'sell_goods' } }

    let fileIndex = 0

    let successList = []

    return new Promise((resolve, reject) => {

        if(showToast){

            uni.showToast({
                title: `正在上传`,
                icon: 'none',
            })
        }
    

        (function uploadFileFun() {

            uploadFunc(url, filePath[fileIndex],obj)
                .then((res) => {
                   
                    fileIndex += 1
                   
                    successList.push(res)
                   
                    if (fileIndex === filePath.length ) {

                        fileIndex = 0
                       
                        resolve(successList)

                        return
                    }
                    setTimeout(() => {
                        uploadFileFun()
                    }, 500)
                })
                .catch((error) => {

                    console.log('error', error)
                    fileIndex = 0

                    if(showToast){
                        uni.showToast({
                            title: '上传失败',
                            icon: 'none',
                        })
            
                    }

                  
                    reject(false)
                })
        })()
    })
}

// 登陆
export function login(fn) {
    console.log('调用登录接口,有session直接return')

    if (uni.getStorageSync('token')) {
        return
    }

    // if( eplatform() == 'H5' ) return

    wx.login({
        success: function (code) {
            console.log('0000000000', code)

            //可以获取appid
            // let appId=uni.getAccountInfoSync().miniProgram.appId
            // console.log(33333333333,uni.getAccountInfoSync())

            uni.request({
                url:
                    baseUrl +
                    `api-u/wechat/program/getInfoAndCheckLogin?code=${res.code}`,
                method: 'get',
                success: (res) => {
                    // console.log('登录接口调用获取结果',res)

                    uni.setStorageSync('reg-open-id', res.data.openid)

                    this.globalData.userWx = res.data

                    //未绑定
                    if (res.code == 0) {
                        if (isMust) {
                            uni.navigateTo({
                                url: '/pages/getuserphone/index',
                            })
                        }
                    }
                    //已绑定
                    else if (res.code == 1) {
                        // that.getLoginToken( res.data ,fn)
                    }

                    // try {
                    //     uni.setStorageSync('session', res.data.data.map.session.map.session);
                    //     uni.setStorageSync('userId', res.data.data.map.userId.map.userId);
                    //     fns.map(item => {
                    //         item()
                    //     })
                    //     fns = []
                    // } catch {
                    //     uni.showToast({
                    //         title: res.data.msg,
                    //         duration: 2000,
                    //         icon: 'none'
                    //     });
                    // }
                },
                // fail: (res) => {
                //     reject(res)
                //     console.log('登陆错误', res)
                // },
                complete: (res) => {
                    //uni.hideLoading()
                },
            })
        },
    })
}

//获取 token , 用 openId  进行登录 然后缓存起来
function getLoginToken(userInfo, fn) {
    this.$axios({
        url: 'sys/login/wechat-focus',
        type: 'POST',
        isFrom: true,
        data: { unionid: userInfo.openid, extensionParams: '0' },
    }).then((res) => {
        if (res) {
            this.Junstroge.set('token', res.access_token, 1)

            fn && fn()

            this.getUserDetail()
        }
    })
}
//拿一次用户信息
function getUserDetail() {
    this.$axios({ url: 'api-u/users/get/usermsg?token' }).then((res) => {
        this.globalData.userInfo = res.data
    })
}
